<template>
  <div>
    <van-nav-bar
  class="user"
  title="个人信息"
  left-arrow
  @click-left="$router.back()"
/>
   
        <input 
          type="file" 
          hidden 
          id="file"
          accept="image/*" 
          ref="file"
          @change="change"
          >
        <van-cell title="头像" center>
          <label for="file">
          <van-image
            width="50"
            height="50"
            round
            fit="cover"
             
            :src="userInfo.avatar" />

          </label>
        </van-cell>
  
        <van-cell title="昵称" is-link :value="userInfo.nickname" />
        <van-cell title="性别" is-link :value="userInfo.sex" />
        <van-cell title="生日" is-link :value="userInfo.birthday" />

    <div style="margin: 16px;">
        <van-button block type="info" color='#07c160' native-type="submit" @click="submit">确定</van-button>
    </div>

    <div>
        <router-link to="/reg"></router-link>
    </div>

  </div>
</template>

<script>
import { Cell, CellGroup ,Form ,Uploader ,Image as VanImage } from 'vant';
import { mapActions } from 'vuex';
import {editUserInfo} from '../api/user'
export default {
  name:'userInfo',
  data(){
    return{
      userInfo:{}
    }
  },
  
  watch:{
    //数据无污染  刷新后也能拿到
    '$store.state.userInfo':{
      immediate:true,  //初始化后 立即进行监听
      handler(n,o){
        this.userInfo = JSON.parse(JSON.stringify(n))
      }
    }
  },
  
  components:{
    [Cell.name]:Cell,
    [CellGroup.name]:CellGroup,
    [Form.name]:Form,
    [Uploader.name]:Uploader  ,
    [VanImage.name]:VanImage 
  },
  methods: {
    ...mapActions(['upload']),
     async change(e){
      console.log();  //没有使用vant 封装vant的

      let file  = e.target.files[0]; //二进制
      // 前端预览  FileReader  base64
      // 2 URL.createObjectURL   前端预览方法一

      this.userInfo.file = file
      let fileReader = new FileReader();
      fileReader.readAsDataURL(file);
      fileReader.onload = (e)=>{
        this.userInfo.avatar = e.target.result
      }
      
     },
     //submit
      async submit(){
        let {_id,nickname,avatar,file,sex='',birthday=''} = this.userInfo;

        if(file){
          let fileList = [{
            file,
          }]  //和vant上传组件形状一样
         let res = await this.upload(fileList)
          avatar = res[0]

        }
        editUserInfo({
          uid:_id,nickname,avatar,sex,birthday
        }).then(res=>{
          console.log(res)
          // 更新成功后 需要返回 更新下vuex的数据
          //最快方案 重新调接口
        })
      }
    },
  }
</script>

<style>

</style>